package com.xmsx.back.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtil {
    /**
     * 过期时间15min
     */
    private static final long EXPIRE_TIME = 30 * 60 * 1000;
    /**
     * token私钥
     */
    private static final String TOKEN_SECRET = "hi4od2h342cv3sd45kdn78932cb4scr3r";

    /**
     *生成签名，15min后过期
     * @param username
     * @return
     */
    public static String sign(String username){
        //过期时间
        Date date = new Date(System.currentTimeMillis()+EXPIRE_TIME);
        //私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        Map<String,Object> header = new HashMap<>(2);
        header.put("typ","JWT");
        header.put("alg","HS256");
        //附带username信息，生成签名
        return JWT.create().withHeader(header)
                .withClaim("username",username)
                .withExpiresAt(date)
                .sign(algorithm);
    }

    /**
     * 校验token是否正确
     * @param token 密钥
     * @return 是否正确
     */
    public static boolean verify(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return  true;

        }catch (Exception exception){
            return false;
        }
    }
}
